package cn.lzd.mr.case2;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by lzd on 2018/5/31.
 */
public class Rdemo extends Reducer<Text, IntWritable, Text, IntWritable> {

    List<Bean> list = new ArrayList<>();

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
        int count = 0;
        for (IntWritable value : values) {
            count += value.get();
        }

        list.add(new Bean(key.toString(), count));
    }

    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        Configuration configuration = context.getConfiguration();
        int anInt = configuration.getInt("top.n", 2);

        Collections.sort(list);

        list.stream()
                .limit(anInt)
                .forEach((x) -> {
                    try {
                        context.write(new Text(x.getSite()), new IntWritable(x.getCount()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
    }
}
